#######################################################################
# This converts a file written in makefile syntax into one that can be included
# by CMake.

# Input variables
#
# verbose:BOOL=<>          OFF: Be as quiet as possible (default)
#                          ON : Extra output
#
# input_file:FILEPATH=<>   Path to dependency file in makefile format
#
# output_file:FILEPATH=<>  Path to file with dependencies in CMake readable variable
#

file(READ ${input_file} depend_text)

if(NOT "${depend_text}" STREQUAL "")

  string(REPLACE "\\ " " " depend_text ${depend_text})
  string(REGEX REPLACE "^.* : " "" depend_text ${depend_text})
  string(REGEX REPLACE "[ \\\\]*\n" ";" depend_text ${depend_text})

  set(dependency_list "")

  foreach(file ${depend_text})

    string(REGEX REPLACE "^ +" "" file ${file})

    if(NOT EXISTS "${file}")
      if(EXISTS "/${file}")
        set(file "/${file}")
      else()
        if(verbose)
          message(WARNING " Removing non-existent dependency file: ${file}")
        endif()
        set(file "")
      endif()
    endif()

    if(file AND NOT IS_DIRECTORY "${file}")
      get_filename_component(file_absolute "${file}" ABSOLUTE)
      list(APPEND dependency_list "${file_absolute}")
    endif()

  endforeach()

else()
  # message("FOUND NO DEPENDS")
endif()

list(REMOVE_DUPLICATES dependency_list)
list(SORT dependency_list)

foreach(file ${dependency_list})
  string(APPEND sycl_depend " \"${file}\"\n")
endforeach()

file(WRITE ${output_file} "# Generated by: make2cmake.cmake\nSET(SYCL_DEPEND\n ${sycl_depend})\n\n")
